package stack;

import java.util.Arrays;

/**
 * @author tongchen
 * @create 2022-10-17 10:17
 */
public class Stack {
    public static void main(String[] args) {
        java.util.Stack<Character> stack2=new java.util.Stack<>();
        Stack stack1 = new Stack(5);
       // System.out.println(stack1.peek());
        stack1.push(1);
        System.out.println(stack1.peek());
        stack1.push(2);
        stack1.push(3);
        stack1.push(4);
        stack1.push(4);
        stack1.push(4);
        stack1.push(4);
        System.out.println(stack1.peek());
//        stack1.pop();
//        stack1.pop();
//        stack1.pop();
//        stack1.pop();
//        stack1.peek();
        System.out.println(stack1.empty());
    }
    //用数组模拟实现栈空间
    final int COUNT=5;
    int size;
    int[]stack;

    public Stack() {
        //默认容量为5
        this.stack=new int[COUNT];
    }

    public Stack(int length) {
        //对length的合法性进行校验
        if(length<0){
            throw new RuntimeException("输入的长度不合法");
        }
        this.stack=new int[length];
    }

    public int push(int e){
       //先判断是否需要扩容
       ensureCapacity();
       stack[size++]=e;
       return e;
    }
    public int pop(){
        //判断栈中是否存在元素
        if(size==0){
            throw new RuntimeException("栈为空，无法取出元素");
        }
        return stack[size--];
    }

    public int peek(){

        //判断栈中是否有元素
        if(empty()){
            throw new RuntimeException("栈为空，无法查看栈顶元素");
        }
        return stack[size-1];
    }
    public int size(){
        return size;
    }
    public boolean empty(){
        if(size==0){
            return  true;

        }
        return false;
    }
    //扩容操作
    private void ensureCapacity(){
if(size>= stack.length){
    stack= Arrays.copyOf(stack,size*2);
}
    }
}
